package com.shxc.smarttrade.login.activity;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.shxc.smarttrade.R;
import com.shxc.smarttrade.base.NoActionBarBaseActivity;
import com.shxc.smarttrade.currency.model.CurrencyModel;
import com.shxc.smarttrade.info.Contents;
import com.shxc.smarttrade.utils.analysis.JsonAnalysisModel;
import com.shxc.smarttrade.utils.analysis.JsonAnalysisUtils;
import com.shxc.smarttrade.utils.AppUtils;
import com.shxc.smarttrade.utils.MyOkHttpUtils;
import com.shxc.smarttrade.utils.ToastUtils;

import org.xchris.view.annotation.ContentView;
import org.xchris.view.annotation.Event;
import org.xchris.view.annotation.ViewInject;

import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;

/**
 * 注册页面
 */
@ContentView(R.layout.activity_login_register)
public class LoginRegiterActivity extends NoActionBarBaseActivity {

    private InputMethodManager imm;

    @ViewInject(R.id.email_warning)
    TextView email_warning;
    @ViewInject(R.id.email_edittext)
    EditText email_edittext;
    @ViewInject(R.id.email_line)
    View email_line;
    @ViewInject(R.id.pass_warning)
    TextView pass_warning;
    @ViewInject(R.id.pass_edittext)
    EditText pass_edittext;
    @ViewInject(R.id.visible_imageview)
    ImageView visible_imageview;
    @ViewInject(R.id.pass_line)
    View pass_line;
    @ViewInject(R.id.register_textview)
    TextView register_textview;


    private int RED = Color.parseColor("#E24C4F");
    private int BLUE = Color.parseColor("#141F2B");
    private int GRAY = Color.parseColor("#B3B3B3");
    private int UNCLICK = Color.parseColor("#50141F2B");

    private String email = "";
    private String pass = "";

    private boolean canSee = false;

    @Event({R.id.close_imageview,R.id.register_textview, R.id.visible_imageview,R.id.notice_view})
    private void onClickk(View view) {

        switch (view.getId()) {
            case R.id.close_imageview:
                finish();
                break;
            case R.id.register_textview:
                //注册
                register();
                break;
            case R.id.visible_imageview:
                canSee = !canSee;
                if (canSee) {
                    visible_imageview.setImageResource(R.mipmap.xianshi_icon);
                    pass_edittext.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    visible_imageview.setImageResource(R.mipmap.yingcang_icon);
                    pass_edittext.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
                break;
            case R.id.notice_view:
                JumpTo(LoginNoticeActivity.class);
                break;
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        imm = (InputMethodManager) this
                .getSystemService(Context.INPUT_METHOD_SERVICE);

        setListener();
        isEnable();
    }

    private void setListener() {

        //判断是否获取焦点 - email
        email_edittext.setOnFocusChangeListener(new android.view.View.
                OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    // 此处为得到焦点时的处理内容
                    email_line.setBackgroundColor(BLUE);
                } else {
                    // 此处为失去焦点时的处理内容
                    email_line.setBackgroundColor(GRAY);
                    checkContent();
                }
            }
        });

        //判断内容 - email
        email_edittext.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0) {
                    email_warning.setVisibility(View.VISIBLE);
                    email_warning.setTextColor(GRAY);
                    email_warning.setText("电子邮箱");
                } else {
                    email_warning.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                isEnable();
            }
        });

        //判断是否获取焦点 - pass
        pass_edittext.setOnFocusChangeListener(new android.view.View.
                OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    // 此处为得到焦点时的处理内容
                    pass_line.setBackgroundColor(BLUE);
                } else {
                    // 此处为失去焦点时的处理内容
                    pass_line.setBackgroundColor(GRAY);
                    checkContent();
                }
            }
        });

        //判断内容 - pass
        pass_edittext.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0) {
                    pass_warning.setVisibility(View.VISIBLE);
                    pass_warning.setTextColor(GRAY);
                    pass_warning.setText("密码");
                } else {
                    pass_warning.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                isEnable();
            }
        });
    }

    private void isEnable() {
        int errors = 0;
        email = email_edittext.getText().toString();
        pass = pass_edittext.getText().toString();
        //电子邮箱
        if (AppUtils.isEmpty(email)) {
            errors++;
        } else if (!AppUtils.isEmail(email)) {
            errors++;
        }

        if (AppUtils.isEmpty(pass)) {
            errors++;
        } else if (pass.length() < 6 || pass.length() > 16 || AppUtils.isNumeric(pass) || pass.matches("^[a-zA-Z]*")) {
            errors++;
        }

        if (errors == 0) {
            register_textview.setEnabled(true);
            register_textview.setBackgroundColor(BLUE);
        } else {
            register_textview.setEnabled(false);
            register_textview.setBackgroundColor(UNCLICK);
        }
    }

    //校验输入内容
    private void checkContent() {

        int errors = 0;

        email = email_edittext.getText().toString();
        pass = pass_edittext.getText().toString();

        //电子邮箱
        if (AppUtils.isEmpty(email)) {
            email_warning.setVisibility(View.GONE);
            errors++;
        } else if (!AppUtils.isEmail(email)) {
            email_warning.setVisibility(View.VISIBLE);
            email_warning.setTextColor(RED);
            email_warning.setText("请输入有效的邮箱");
            errors++;
        } else {
            email_warning.setVisibility(View.VISIBLE);
            email_warning.setTextColor(GRAY);
            email_warning.setText("电子邮箱");
        }

        if (AppUtils.isEmpty(pass)) {
            pass_warning.setVisibility(View.GONE);
            errors++;
        } else if (pass.length() < 6 || pass.length() > 16 || AppUtils.isNumeric(pass) || pass.matches("^[a-zA-Z]*")) {
            pass_warning.setVisibility(View.VISIBLE);
            pass_warning.setTextColor(RED);
            pass_warning.setText("密码必须由6-16位数字与字母组成");
            errors++;
        } else {
            pass_warning.setVisibility(View.VISIBLE);
            pass_warning.setTextColor(GRAY);
            pass_warning.setText("密码");
        }

        if (errors == 0) {
            register_textview.setEnabled(true);
            register_textview.setBackgroundColor(BLUE);
        } else {
            register_textview.setEnabled(false);
            register_textview.setBackgroundColor(UNCLICK);
        }
    }

    // 点击EditText以外的任何区域隐藏键盘
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {

        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (v != null) {
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
        return super.onTouchEvent(event);
    }

    /**
     * Overrides the pending Activity transition by performing the "Enter" animation.
     * 跳转到新activity时的演示动画
     */
    protected void overridePendingTransitionEnter() {
        overridePendingTransition(R.anim.slide_from_right, R.anim.slide_to_left);
    }

    //注册
    private void register() {
        loadingDialog.show();
        Map<String, Object> map = new HashMap<>();
        map.put("email", email);
        map.put("password", pass);

        MyOkHttpUtils.getServiceDatas(map, Contents.REGISTER, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void success(String response, int d) {
                if (response != null) {
                    JsonAnalysisModel jam = JsonAnalysisUtils.jsonAnalysis(response, CurrencyModel.class);
                    if (jam.isSuccess()) {
                        CurrencyModel model = (CurrencyModel) jam.getData();
                        if (model.getErr_code().equals("0")) {
                            ToastUtils.showToast("注册成功");
                            spImp.setEmail(email);
                            finish();
                        }else{
                            ToastUtils.showToast(jam.getMsg());
                        }

                    } else {
                        ToastUtils.showToast(jam.getMsg());
                    }
                }
                loadingDialog.dismiss();
            }

            @Override
            public void faild(Call call, Exception e, int id) {
                loadingDialog.dismiss();
            }
        });
    }
}
